<?php
include_once($adm_data_server."lib/php/resources_adm.php");

class search extends module {

	var $host_name='';

	function get_hash_code()
	{
		if ($this->q_param['s_result_area_id'] && $this->q_param['s_result_area_id']==$this->tarea_id) {
			foreach ($_GET as $k => $v) {
				if (!preg_match('~\d~',$k)) {
					//$k - не пропарсен в q_param
					$this->q_param[$k]=$v;
				}
			}
		}

		$p=parent::get_hash_code();
		if($this->version==1)return 0;
		return md5($p.$_COOKIE['client_id'].$_COOKIE['random_number']);
	}
	function get_url($page_id){
		$page_row=sql_select("SELECT * FROM PAGE WHERE VERSION={$this->version} AND PAGE_ID=$page_id");
		$parent=$page_row[0]["PARENT_ID"];
		$redir_path=$page_row[0]["DIR_NAME"]."/";
		while($parent!=0){
			$parent_rows=sql_select("SELECT PARENT_ID,DIR_NAME FROM PAGE WHERE PAGE_ID=$parent");
			$parent_rows=chose_version($parent_rows,"PARENT_ID");
			$redir_path=$parent_rows[0]["DIR_NAME"]."/".$redir_path;
			$parent=$parent_rows[0]["PARENT_ID"];
		}

		return "/".$redir_path;
	}

	function get_search_location()
	{
		return '/cgi-bin/common/search.cgi';
	}

	function get_search_results()
	{
		global $common_data_server;
		$template=$common_data_server."/module_templates/search/".$this->view_param["template"].'/search.htm';
		$q_string = "s_result_area_id{$this->tarea_id}=".$this->tarea_id.
		"&q=".urlencode($this->querier($this->q_param["q"])).
		"&ul=".urlencode($this->q_param["ul"]).
		"&ps=".urlencode(( $this->q_param["ps"] > 0  ? $this->q_param["ps"] : 10)).
		"&wf=".urlencode($this->q_param["wf"])
		."&m=".urldecode($this->q_param["m"])
		."&np=".urldecode($this->q_param["np"])
		."&sy=".urldecode($this->q_param["sy"])
		."&sp=".urldecode($this->q_param["sp"])
		."&wm=".urldecode($this->q_param["wm"])
		;
		global $protected_access,$db_type;
		if (!isset($db_type)) {
			$db_type='mysql';
		}
		if ($protected_access) {
			if (check_autorization()) {
				//авторизован
				switch ($protected_access) {
					case 'isRegistratedClient':
						//
						break;

					case 'isRightClient':
						$q_string.='&fl=isRightClient_'.$db_type
						.'&CLID='.intval($_COOKIE['client_id'])
						.'&R_N='.db_quote($_COOKIE['random_number'])
						;
						break;

					case 'isRightGroup':
						$q_string.='&fl=isRightGroup_'.$db_type
						.'&CLID='.intval($_COOKIE['client_id'])
						.'&R_N='.db_quote($_COOKIE['random_number'])
						;
						break;

					default:
						$q_string.='&fl=UN_PROTECTED_'.$db_type;
						break;
				}
			}
			else {
				$q_string.='&fl=UN_PROTECTED_'.$db_type;
			}
		}

		putenv('UDMSEARCH_TEMPLATE='.$template);
		putenv('QUERY_STRING='.$q_string);
		return $this->TranslateSearchResult(shell_exec($common_data_server.'/mnogosearch/bin/search.cgi'));
	}
	#----------------------------------------------------------------------------------------------------------------------------
	/*
	*    Функция заменяет некоторые переменные в результатах поиска системными словами
	*/

	function TranslateSearchResult($result)
	{
		// Слова, которые нам нужно искать
		/*$sysw_names = array(
		"SYSW_SEARCH_RESULT_TIME",
		"SYSW_SEARCH_RESULT_SECONDS",
		"SYSW_SEARCH_RESULT_DOCUMENTS",
		"SYSW_SEARCH_RESULT_FROM",
		"SYSW_SEARCH_RESULT_FOUND",
		"SYSW_SEARCH_RESULT_BACK",
		"SYSW_SEARCH_RESULT_NEXT",
		"SYSW_SEARCH_RESULT_NOTFOUND",
		"SYSW_SEARCH_RESULT_NOQUERY",
		"SYSW_SEARCH_RESULT_ERROR");

		$c = count($sysw_names);
		// Собираем sql
		$sysw_sql = "'".$sysw_names[0]."'";
		for($i = 1; $i < $c; $i++)
		{
		$sysw_sql .= ", '".$sysw_names[$i]."'";
		}*/

		// Вытаскиваем значения системных слов
		$sysw_values = sql_select("SELECT SYSTEM_NAME, VALUE FROM SYSTEM_WORD WHERE LANG_ID = ".$this->lang_id.
		" AND PRG_MODULE_ID=(SELECT PRG_MODULE_ID FROM PRG_MODULE WHERE CLASS_NAME='search')");

		// Теперь реплейсим регулярками
		$regexp = array();
		$replacement = array();
		foreach($sysw_values as $sw)
		{
			$regexp[] = "/<TMPL_VAR[\s]+NAME[\s]*=[\s]*[\"|\']".$sw['SYSTEM_NAME']."[\"|\'][\s]*>/i";
			$replacement[] = $sw['VALUE'];
		}

		$regexp[]='~Content-type: text/html; charset=.+~';$replacement[]='';
		$s= preg_replace($regexp, $replacement, $result);
		$regexp = array();
		$regexp[]='~(<a[^>]+href=[\'"])([^\'"]+)([\'"])+~i';$call_back=array($this,'parse_ancor');

		$s=preg_replace_callback($regexp,$call_back,$s);
		return $s;
	}

	function parse_ancor($m)
	{
		if (preg_match('~q=[^&]~',$m[2])) {
			$rx=array();
			$r=array();
			$rx[]='~[&]?(amp;)?fl=[^&]+~';$r[]='';
			$rx[]='~[&]?(amp;)?CLID=[^&]+~';$r[]='';
			$rx[]='~[&]?(amp;)?R_N=[^&]+~';$r[]='';
			$m[2]=preg_replace($rx,$r,$m[2]);
		}
		return $m[1].$m[2].$m[3];
	}

	function content_init() {
		global $common_data_server;
		switch ($this->view_param["used_type"]) {
			case "quick" :  $template=$common_data_server."module_templates/search/".$this->view_param["template"]."/search_quick.vtmpl"; break;
			case "advanced" :  $template=$common_data_server."module_templates/search/".$this->view_param["template"]."/search_advanced.vtmpl"; break;
		}
		//$this->ShowMass($template);
		if ( file_exists( $template ) ) {

			//какой сайт индексировать?
			//получаем параметр ul
			$sql="
						select
								SITE.*
						from
							SITE,PAGE
						where
							PAGE.PAGE_ID={$this->page_id}
							and PAGE.SITE_ID=SITE.SITE_ID
						";
			$rs=sql_select($sql);
			$lang_dir=sql_select("SELECT * FROM LANG WHERE LANG_ID='{$this->lang_id}'");
			$this->host_name='http'.($_SERVER['HTTPS'] == 'on' ? 's' : '')."://".$rs[0]['HOST'];
			if ($this->q_param['ul']=='') {
				$this->q_param['ul']=$this->host_name."/".$lang_dir[0]["ROOT_DIR"]."/";
			}




			//количество ссылок на страницу:
			if (!(int)$this->q_param['ps']){
				$this->q_param['ps']=$this->view_param['page_num'];
			}

			//где производить поиск?
			if ($this->q_param['wf']==''){
				$this->q_param['wf']=2221;//во всех частях документа
			}

			//использование синонимов
			if ($this->q_param['sy']==''){
				$this->q_param['sy']=$this->view_param["used_type"]=='advanced'?1:0;//да
			}

			//Words forms
			if ($this->q_param['sp']==''){
				$this->q_param['sp']=$this->view_param["used_type"]=='advanced'?1:0;//все 0 - точно
			}

			//Search for
			if ($this->q_param['wm']==''){
				$this->q_param['wm']=$this->view_param["used_type"]=='advanced'?'wrd':'sub';//Whole word
			}

			//Совпадение
			if ($this->q_param['m']==''){
				$this->q_param['m']='all';//вся фраза
			}


			//быстрый поиск
			if ($this->view_param["used_type"] == 'quick' ){

				$vtmpl=new vlibTemplate($template);
				if ($this->view_param["page"] != ''){
					$path=$this->get_url($this->view_param["page"]);
				}
				$vtmpl->setVar('TAREA_ID',$this->getTAreaId($this->view_param["page"]));
				$vtmpl->setVar('SEARCH_PAGE_URL',$path);
				if ($this->q_param['q']!=''){
					$vtmpl->setVar('SEARCH_RESULT',$this->GetSimpleResult());
				}
				$vtmpl->setVar($this->q_param);
				$vtmpl->setVar($this->view_param);
				$this->body = $vtmpl->grab();
			}
			//--/быстрый поиск


			//расширенный поиск
			if ($this->view_param["used_type"] == 'advanced' ){
				$this->modAdvancedSearch($template);
			}
			//--/расширенный поиск

		}else{
			$this->body = "Шаблон $template не найден";
		}
	}


	#-------------------------------------------------------------------------------------------------------------------------
	/**
	* @return void
	* @param unknown $template
	* @desc Вариант использования расширенный поиск
	*/
	function modAdvancedSearch($template)
	{

		// поправить запрос
		//print "SELECT SITE_ID FROM PAGE WHERE PAGE_ID='".$this->page_id."'";
		$sql_site_row=sql_select("SELECT SITE_ID FROM PAGE WHERE PAGE_ID='".$this->page_id."' AND LANG_ID='".$this->lang_id."'");
		$sql_first_page_row=sql_select("SELECT PAGE_ID,PAGE.DIR_NAME FROM PAGE WHERE PARENT_ID=0 AND SITE_ID='".$sql_site_row[0][0]."' AND LANG_ID='".$this->lang_id."'");
		$sql_result_set=sql_select("SELECT PAGE.PAGE_ID AS PAGE_ID, PAGE.PARENT_ID AS PARENT_ID, PAGE.NAME AS NAME, PAGE.PAGE_ORDER AS PAGE_ORDER, PAGE.VERSION AS VERSION, SITE_ID,PAGE.DIR_NAME FROM PAGE WHERE SITE_ID = '".$sql_site_row[0][0]."' AND LANG_ID='".$this->lang_id."' AND IS_MENU_PUBLISHED=1 AND VERSION='".$this->version."'");
		$sql_result_set=chose_version($sql_result_set,"PAGE_ID");
		$rs = get_tree("PAGE_ID", $sql_first_page_row[0][0], "PAGE_ORDER",'',0, '', $sql_result_set);
		// создаем массив для списка разделов по которым будет производится поиск
		$search_list=array();
		//print urldecode($this->q_param["ul"]);

		/*marhipov*/
		$cur_deep=-1;
		$cur_path="/{$sql_first_page_row[0]["DIR_NAME"]}/";
		/*marhipov*/

		while($current_row = current($rs)) {
			if ($current_row["TREE_DEEP"]+1 > $this->view_param["tree_deep"]){
				next($rs);
			}else{
				$list_item['NAME']=str_repeat("&nbsp;&nbsp;", ($current_row["TREE_DEEP"]+1) * 2).$current_row["NAME"];
				//$list_item['URL']='http'.($_SERVER['HTTPS'] == 'on' ? 's' : '').'://'.$_SERVER["SERVER_NAME"].$this->get_url($current_row["PAGE_ID"]);

				/*marhipov*/
				if($cur_deep<$current_row["TREE_DEEP"])
				{
					$cur_path.="{$current_row["DIR_NAME"]}/";
				}
				elseif($cur_deep==$current_row["TREE_DEEP"])
				{
					$cur_path=preg_replace("@/[\w-]+/$@","/{$current_row["DIR_NAME"]}/",$cur_path);
				}
				else
				{
					$regexp="/".str_repeat("[\\w-]+/",$current_row["TREE_DEEP"]+1);
					$regexp="@^({$regexp}).+@";
					$cur_path=preg_replace($regexp,"\\1",$cur_path)."{$current_row["DIR_NAME"]}/";
				}
				$list_item['URL']=$this->host_name.$cur_path;
				$cur_deep=$current_row["TREE_DEEP"];
				/*marhipov*/

				if ($list_item['URL'] == urldecode($this->q_param["ul"])){
					$list_item["SELECTED"]=1;
				}else{
					$list_item["SELECTED"]=0;
				}
				array_push($search_list,$list_item);
				next($rs);
			}
		}
		// формируем ACTION
		if ($this->view_param["page"] != ''){
			$path=$this->get_url($this->view_param["page"]);
		}
		global $common_data_server;
		// формируем строку поиска

		$vtmpl=new vlibTemplate($template);
		$vtmpl->setVar('ALL_SITE',$this->host_name."/");
		$vtmpl->setVar('SEARCH_PAGE_URL',$path);
		$vtmpl->setVar('TAREA_ID',$this->tarea_id);
		$vtmpl->setVar('q',$this->q_param["q"]);

		$vtmpl->setVar('wf_'.$this->q_param["wf"],1);
		$vtmpl->setVar('ps_'.$this->q_param["ps"],1);
		$vtmpl->setVar('wm_'.$this->q_param["wm"],1);
		$vtmpl->setVar('sp_'.$this->q_param["sp"],1);
		$vtmpl->setVar('sy_'.$this->q_param["sy"],1);
		$vtmpl->setVar('m_'.$this->q_param["m"],1);
		$vtmpl->setVar('TAREA_ID',$this->getTAreaId($this->view_param["page"]));
		//bencher_p('search.cgi');
		if (urldecode($this->q_param["q"])){
			//ищем, только если задан критерий поиска
			$search_res = $this->get_search_results();
			$vtmpl->setVar('SEARCH_RESULT',$search_res);
		}
		//$this->ShowMass(bencher_p('search.cgi'));

		$vtmpl->setLoop("SECTION_LIST", $search_list );
		$vtmpl->setVar($this->q_param);
		$vtmpl->setVar($this->view_param);
		$this->body = $vtmpl->grab();
	}//function modAdvancedSearch

	#-------------------------------------------------------------------------------------------------------------------------
	function GetSimpleResult()
	{
		return $this->get_search_results();
	}//function GetSimpleResult

	function querier($q)
	{
		return $q;
		//сюда можно добавить предварительную обработку запроса на поиск.
	}

	#-------------------------------------------------------------------------------------------------------------------------

	function ShowMass($arr,$mess='',$release=false) //<= for debug
	{
		if (!$release || $_GET['debug']){
			print "<pre>$mess\n";
			print_r($arr);
			print "\n</pre>";
		}
	}



}
